package com.zxjbyte.yiyi.module.system.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.common.constant.RedisKeyDefine;
import com.zxjbyte.yiyi.framework.common.util.CollXUtil;
import com.zxjbyte.yiyi.framework.common.util.JsonUtil;
import com.zxjbyte.yiyi.framework.redis.manager.RedisDao;
import com.zxjbyte.yiyi.module.system.domain.entity.DictDataPO;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 字典值缓存工具类
 *
 * @Author zhangxingjia
 * @Date 2024/2/22 16:16
 * @Version: 1.0
 */
@UtilityClass
public class DictCacheUtil {

    public RedisDao redisDao;

    public RedisDao getRedisDao(){
        if(redisDao == null){
            redisDao = SpringUtil.getBean(RedisDao.class);
        }
        return redisDao;
    }

    /**
     * 设置字段缓存
     * @param dictType
     * @param dictDataList
     */
    public void setDict(String dictType, List<DictDataPO> dictDataList){
        getRedisDao().set(getRedisKey(dictType), JsonUtil.toJsonAsString(dictDataList));
    }

    public List<DictDataPO> getDict(String dictType){
        String jsonStr = getRedisDao().get(getRedisKey(dictType));
        if(StrUtil.isNotBlank(jsonStr)){
            return JsonUtil.parseList(jsonStr, DictDataPO.class);
        }
        return null;
    }

    public DictDataPO getOneDict(String dictType){
        List<DictDataPO> list = getDict(dictType);
        if(CollXUtil.isNotEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    public Map<String, DictDataPO> getDictMap(String dictType){
        List<DictDataPO> list = getDict(dictType);
        if(CollXUtil.isNotEmpty(list)){
            return list.stream().collect(Collectors.toMap(DictDataPO::getDictValue, Function.identity(), (k1, k2) -> k1));
        }
        return null;
    }

    public Map<String, String> getValueLabelMap(String dictType){
        List<DictDataPO> list = getDict(dictType);
        if(CollXUtil.isNotEmpty(list)){
            return list.stream().collect(Collectors.toMap(DictDataPO::getDictValue, DictDataPO::getDictLabel, (k1, k2) -> k1));
        }
        return null;
    }

    public String getDictLabel(String dictType, String dictValue){
        Map<String, String> map = getValueLabelMap(dictType);
        if(CollXUtil.isNotEmpty(map)){
            return map.get(dictValue);
        }
        return null;
    }

    /**
     * 移除指定缓存
     * @param dictType
     */
    public void removeDict(String dictType){
        getRedisDao().del(getRedisKey(dictType));
    }

    private String getRedisKey(String dictType){
        return RedisKeyDefine.getDictKey(dictType);
    }
}
